package com.crazy.util;

import com.crazy.entity.ImagePosition;
import com.itextpdf.text.pdf.BaseFont;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

/**
 * @author panyonghui
 * @describe 图片工具类
 * @date 2022/1/14 15:42
 */
public class ImageUtils {
    /*Thumbnails依赖包
    <dependency>
        <groupId>net.coobird</groupId>
        <artifactId>thumbnailator</artifactId>
        <version>0.4.8</version>
    </dependency>*/

    /**
     * 宽度倍数
     */
    private static final float widthTimes = 1.5f;

    /**
     * 宽高倍数
     */
    private static final int TIMES = 2;

    /**
     * @describe 压缩图片
     * @param filePath 原文件路径(/home/file/test.png)
     * @param resultPath 结果保存路径(/home/file/test_res.png)
     * @param scale 图片大小（长宽）压缩比例 从0-1，1表示原图
     * @param quality 图片质量压缩比例 从0-1，越接近1质量越好
     * @return void
     */
    public static void compressImage(String filePath, String resultPath, float scale, float quality) throws IOException {
        File file = new File(filePath);
        try(OutputStream os = new FileOutputStream(resultPath)){
            Thumbnails.of(file)
                    // 图片大小（长宽）压缩比例 从0-1，1表示原图
                    .scale(scale)
                    // 图片质量压缩比例 从0-1，越接近1质量越好
                    .outputQuality(quality)
                    .toOutputStream(os);
        } catch (IOException e){
            throw e;
        }
    }

    /**
     * @describe 图片旋转
     * @auther crazy_cat
     * @date 2022/1/14 16:30
     * @param filePath 原文件路径(/home/file/test.png)
     * @param resultPath 结果保存路径(/home/file/test_res.png)
     * @param rotate 旋转角度（1-360，90f-向右旋转90度）
     * @return void
     * @modify
     */
    public static void rotateImage(String filePath, String resultPath, float rotate) throws IOException {
        File file = new File(filePath);
        try(OutputStream os = new FileOutputStream(resultPath)){
            Thumbnails.of(file)
                    // 图片比例
                    .scale(1)
                    // 旋转角度
                    .rotate(rotate)
                    .toOutputStream(os);
        } catch (IOException e){
            throw e;
        }
    }

    /**
     * @describe 添加水印
     * @auther crazy_cat
     * @date 2022/8/9 16:22
     * @param filePath
     * @param waterMarkContent
     * @param imagePosition
     * @return void
     * @modify
     */
    public static void markWatermark(String filePath, String waterMarkContent, ImagePosition imagePosition) throws Exception {
        File file = new File(filePath);
        if (file == null
                || !file.isFile()
                || !file.exists()
                || !file.canRead()) {
            throw new Exception("文件无效");
        }
        // 加水印
        BufferedImage bufImg = ImageIO.read(file);

        // 字体样式
        Font font = imagePosition.getFont();

        // 宽度
        int imgWidth = bufImg.getWidth();

        // 高度
        int imgHeight = bufImg.getHeight();

        // 字体高度
        int fontHeight = font.getSize();

        // 字体宽度
        int fontWidth = font.getSize() * getTextLength(waterMarkContent);

        // 横向间隔
        int marginX = imagePosition.getMarginX();
        marginX += fontWidth;

        // 纵向间隔
        int marginY = imagePosition.getMarginY();
        marginY += fontHeight;

        // 透明度
        float transparent = imagePosition.getTransparent();

        // 字体颜色
        Color color = imagePosition.getColor();

        // 创建绘图工具
        Graphics2D g = bufImg.createGraphics();

        // 画入原始图像
        g.drawImage(bufImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);

        // 设置倾斜角度
        g.rotate(Math.toRadians(330), (double) imgWidth / TIMES, (double) imgHeight / TIMES);

        //根据图片的背景设置水印颜色
        g.setColor(color);

        //设置字体
        g.setFont(font);

        // 设置水印透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, transparent));

        for (int x = -imgWidth; x < imgWidth * TIMES; x += marginX) {
            for (int y = -imgHeight / TIMES; y < imgHeight * TIMES; y += marginY) {
                //画出水印
                g.drawString(waterMarkContent, x, y);
            }
        }
        // 销毁绘图工具
        g.dispose();
        try(OutputStream outputStream = new FileOutputStream(imagePosition.getTargetPath())) {
            // 保存结果文件
            ImageIO.write(bufImg, imagePosition.getImageType(), outputStream);
        } catch (IOException e) {
            throw e;
        }

    }

    public static int getTextLength(String text) {
        //水印文字长度
        int length = text.length();

        for (int i = 0; i < text.length(); i++) {
            String s = String.valueOf(text.charAt(i));
            if (s.getBytes().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }

    public static void main(String args[]) throws Exception {
        String filePath = "E:\\home\\test\\6E800B0652F1649C0E49BB7CF108AB39.jpg";
        String targetPath = "E:\\home\\test\\6E800B0652F1649C0E49BB7CF108AB39_watermark.jpg";
        ImagePosition imagePosition = new ImagePosition();
        imagePosition.setMarginX(150);
        imagePosition.setMarginY(150);
        imagePosition.setImageType("jpg");
        imagePosition.setTargetPath(targetPath);
        imagePosition.setTransparent(0.3f);
        imagePosition.setColor(Color.RED);
        Font font = new Font("宋体", Font.PLAIN, 20);
        imagePosition.setFont(font);
        String contentText = "" + System.currentTimeMillis();
        markWatermark(filePath,contentText, imagePosition);
    }
}
